<template>
<el-table :data="cartItems" style="width: 1150px;margin: 50px auto;" @selection-change="handleSelectionChange">
  <el-table-column type="selection" width="55" ></el-table-column>
  <el-table-column prop="product.imageUrl" label="商品图片" width="100">
    <template #default="{ row }">
      <img :src="row.product.imageUrl" style="height: 60px;">
    </template>
  </el-table-column>
  <el-table-column prop="product.name" label="商品名称" width="100"></el-table-column>
  <el-table-column label="商品规格" width="120">
    <template #default="{ row }">
      <el-tag @click="showAttributeDialog(row)">{{ row.attributeProduct?.attributeName || '选择规格' }}</el-tag>
    </template>
  </el-table-column>
  <el-table-column prop="attributeProduct.price" label="单价" width="100"></el-table-column>
  <el-table-column prop="product.description" label="描述" width="180"></el-table-column>
  <el-table-column label="优惠券" width="250">
    <template #default="{ row }">
      <el-select
        v-model="row.cart.discountId"
        placeholder="请选择优惠券"
        @change="handleQuantityChange(row.cart)"
      >
        <el-option
          v-for="discount in row.discountInfos"
          :key="discount.discountId"
          :disabled="discount.discountStrategy==2?discount.fullReduction>=calculateSubtotal(row):false"
          :label="`${discount.discountName}（${discount.description}）`"
          :value="discount.discountId"
        >
          <span style="float: left">{{ discount.discountName }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">
          {{ discount.description }}
          </span>
        </el-option>
      </el-select>
    </template>
  </el-table-column>
  <el-table-column prop="brand.brandName" label="商家" width="100"></el-table-column>
  <el-table-column label="数量" width="115">
    <template #default="{ row }">
      <div>
        <el-input-number v-model="row.cart.quantity" size="small" style="width: 90px;" :min="1" :max="10" @change="handleQuantityChange(row.cart)" />
      </div>
    </template>
  </el-table-column>
  <el-table-column label="小计" width="100">
    <template #default="{ row }">
      {{ calculateSubtotal(row) }}
    </template>
  </el-table-column>
  <el-table-column label="到手价" width="100">
    <template #default="{ row }">
      {{ reducePrice(row) }}
    </template>
  </el-table-column>
  <el-table-column label="操作" width="172">
    <template #default="{ row }">
      <el-button type="danger" size="small" :icon="Delete" round @click="deleteCartItemFunc(row.cart.cartId)">删除</el-button>
    </template>
  </el-table-column>
</el-table>
<div>
  <transition name="el-fade-in-linear" style="z-index: 999">
    <div v-if="isShowCart" class="bottom">
      <el-button type="primary" @click="clearCart">清空购物车</el-button>
      <el-button type="success" size="large" @click="toSubmit" style="float: right;margin: 10px;width: 150px;" round>去结算</el-button>
      <span class="price toBold">总价：{{ selectedTotalPrice }}</span>
      <span>
          <el-tag type="primary" size="large">已选择{{ selectedTotalQuantity }}件商品</el-tag>
        </span>
    </div>
  </transition>
</div>
<!-- 添加属性选择对话框 -->
<el-dialog v-model="attributeDialogVisible" title="选择商品规格">
  <el-scrollbar height="300px">
    <!-- 遍历属性列表 -->
    <el-tag
      v-for="attribute in attributeList"
      @click="confirmAttributeSelection(attribute)"
      style="height: 50px;margin: 10px"

    >
      <img :src="attribute.attributeImg" style="width: 50px; height: 50px;">
      {{ attribute.attributeName  }}
      {{ attribute.price  }}
    </el-tag>
  </el-scrollbar>
</el-dialog>
<el-dialog v-model="orderDialogVisible" title="提交订单">
  <el-card>
    <template #header>
      <h3>已选择的商品</h3>
    </template>
    <el-table :data="selectedRows" style="width: 100%; margin-bottom: 20px;">
      <el-table-column prop="product.name" label="产品名"></el-table-column>
      <el-table-column label="规格">
        <template #default="{ row }">
          {{ row.attributeProduct?.attributeName || '未选择' }}
        </template>
      </el-table-column>
      <el-table-column label="单价">
        <template #default="{ row }">
          {{ row.attributeProduct?.price || row.product.price }}
        </template>
      </el-table-column>
      <el-table-column prop="cart.quantity" label="数量"></el-table-column>
      <el-table-column label="优惠券">
        <template #default="{row}">
          <div v-if="row.cart.discountId">
            {{getDiscountInfoByCartDiscountId(row).discountName}}
          </div>
          <div v-else>
            暂无优惠券
          </div>

        </template>
      </el-table-column>
      <el-table-column label="最终价">
        <template #default="{ row }">
          <div v-if="row.cart.discountId">
            <del>{{calculateSubtotal(row)}}</del>
            {{ reducePrice(row) }}
          </div>
          <div v-else>
            {{calculateSubtotal(row)}}
          </div>
        </template>
      </el-table-column>
    </el-table>
    <h3>总价：￥{{ selectedTotalPrice }}</h3>
  </el-card>
  <el-card  style="margin-top: 10px">
    <template #header>
      <h3>选择地址</h3>
    </template>
    <el-form>
      <el-form-item>
        <el-radio-group v-model="selectedAddressId">
          <el-radio v-for="address in addresses" :key="address.addressId" :label="address.addressId" border style="width: 100%">
            {{ address.recipientName }} - {{ address.recipientPhone }} - {{ address.addressDetail }}
            <el-button type="danger" size="small" @click="deleteAddress(address)">删除</el-button>
            <el-button type="warning" size="small" @click="editAddress(address)">修改</el-button>
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="showAddAddressForm = true">添加地址</el-button>
      </el-form-item>
    </el-form>

    <el-form v-if="showAddAddressForm" label-width="100px">
      <el-form-item label="收件人姓名">
        <el-input v-model="newAddress.recipientName"></el-input>
      </el-form-item>
      <el-form-item label="收件人电话">
        <el-input v-model="newAddress.recipientPhone"></el-input>
      </el-form-item>
      <el-form-item label="详细地址">
        <el-input v-model="newAddress.addressDetail"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addAddress2">提交</el-button>
        <el-button @click="showAddAddressForm = false">取消</el-button>
      </el-form-item>
    </el-form>
    <el-form v-if="showEditAddressForm" label-width="100px">
      <el-form-item label="收件人姓名">
        <el-input v-model="editedAddress.recipientName"></el-input>
      </el-form-item>
      <el-form-item label="收件人电话">
        <el-input v-model="editedAddress.recipientPhone"></el-input>
      </el-form-item>
      <el-form-item label="详细地址">
        <el-input v-model="editedAddress.addressDetail"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveEditedAddress">保存</el-button>
        <el-button @click="showEditAddressForm = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <template #footer>
    <el-button @click="orderDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="submitOrder">提交订单</el-button>
  </template>
</el-dialog>
</template>

<script setup >
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElTable, ElTableColumn, ElButton, ElMessage } from 'element-plus';
import { getAddresses, addNewAddress, updateAddress,createOrder,getCartItems, deleteCartItem, updateCartItem, getAttributes } from '@/common/net/api';
import { payGO } from '@/common/net/toPay'
// 添加对话框显示状态的响应式变量
const attributeDialogVisible = ref(false);
// 添加属性列表的响应式变量
const attributeList = ref([]);
// 添加选中属性的响应式变量
const isShowCart = ref(true);
const cartItems = ref([]);
const orderDialogVisible = ref(false);
const addresses = ref([]);
const selectedAddressId = ref(null);
const selectedRows = ref([]);
let currentCart = ref({});
const router = useRouter();

const showAttributeDialog = async (row) => {
  try {
    currentCart.value=row.cart;
    const response = await getAttributes(row.product.productId);
    attributeList.value = response.data;
    attributeDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取商品属性失败');
  }
};
const confirmAttributeSelection = async (row) => {
  console.log(row.price)
  if (row.attributeId) {
    currentCart.value.attributeId=row.attributeId;
    await updateCartItem(currentCart.value);
    await fetchCartItems()
    attributeDialogVisible.value = false;
  }
};
let showAddAddressForm = ref(false);
let showEditAddressForm = ref(false);
const newAddress = ref({
  recipientName: '',
  recipientPhone: '',
  addressDetail: ''
});
const editedAddress = ref({
  addressId: null,
  recipientName: '',
  recipientPhone: '',
  addressDetail: ''
});

const addAddress2 = async () => {
  try {
    const response = await addNewAddress(newAddress.value);
    ElMessage.success('地址添加成功');
    showAddAddressForm.value = false;
    newAddress.value = {
      recipientName: '',
      recipientPhone: '',
      addressDetail: ''
    };
    await fetchAddresses();
  } catch (error) {
    ElMessage.error('地址添加失败');
  }
};

const deleteAddress = async (address) => {
  address.isDel=1
  try {
    await updateAddress(address);
    ElMessage.success('地址删除成功');
    await fetchAddresses();
  } catch (error) {
    ElMessage.error('地址删除失败');
  }
};

const editAddress = (address) => {
  editedAddress.value = { ...address };
  showEditAddressForm.value = true;
};

const saveEditedAddress = async () => {
  try {
    await updateAddress(editedAddress.value);
    ElMessage.success('地址修改成功');
    showEditAddressForm.value = false;
    await fetchAddresses();
  } catch (error) {
    ElMessage.error('地址修改失败');
  }
};

const fetchAddresses = async () => {
  try {
    const response = await getAddresses();
    addresses.value = response.data.data;
  } catch (error) {
    ElMessage.error('获取地址失败');
  }
};
const calculateSubtotal = (row) => {
  let num = 0;
  if (row.attributeProduct){
    num =  row.attributeProduct.price*row.cart.quantity;
    if (row.cart.discountId){
      const discountCal = getDiscountInfoByCartDiscountId(row)
      if (discountCal.discountStrategy==2?discountCal.fullReduction>=num:false) {
        row.cart.discountId=null;
        handleQuantityChange(row.cart)
      }
    }
    return num;
  }else{
    return 0;
  }
};
// 折后价格
const reducePrice = (row) => {
  if (!row.cart.discountId) return calculateSubtotal(row)

  const discountInfo = getDiscountInfoByCartDiscountId(row)
  if (discountInfo.discountStrategy==2){
    return calculateSubtotal(row)-discountInfo.discountValue;
  }else{
    return (calculateSubtotal(row)*discountInfo.discountValue).toFixed(2);
  }
}
const getDiscountInfoByCartDiscountId=(row)=> {
  // 从 row 中获取购物车信息和折扣信息
  const cart = row.cart;
  const discountInfos = row.discountInfos;

  // 获取购物车中的 discountId
  const cartDiscountId = cart.discountId;

  // 在 discountInfos 中找到与 cartDiscountId 匹配的数据
  const matchedDiscountInfo = discountInfos.find((discountInfo) => {
    return discountInfo.discountId === cartDiscountId;
  });

  return matchedDiscountInfo;
}

const selectedTotalPrice = computed(() => {
  return selectedRows.value.reduce((sum, row) => sum + Number(reducePrice(row)), 0).toFixed(2);
});
const handleSelectionChange = (val) => {
  selectedRows.value = val;
};
// 计算选中行的总数量
const selectedTotalQuantity = computed(() => {
  return selectedRows.value.reduce((sum, row) => sum + row.cart.quantity, 0);
});

const handleQuantityChange = async (row) => {
  try {
    await updateCartItem(row);
  } catch (error) {
    ElMessage.error('更新失败');
  }
};

const deleteCartItemFunc = async (cartId) => {
  try {
    await deleteCartItem(cartId);
    ElMessage.success('删除成功');
    await fetchCartItems();
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

const clearCart = async () => {
  // try {
  //   for (const item of cartItems.value) {
  //     await deleteCartItem(item.cartId);
  //   }
  //   ElMessage.success('购物车已清空');
  //   cartItems.value = [];
  // } catch (error) {
  //   ElMessage.error('清空购物车失败');
  // }
};
const fetchCartItems = async () => {
  try {
    const response = await getCartItems(1, 10); // 假设分页参数
    console.log(response);
    cartItems.value = response.data.data.records;
  } catch (error) {
    ElMessage.error('获取购物车商品失败');
  }
};

const toSubmit = async () => {
  try {
    const response = await getAddresses();
    addresses.value = response.data.data;
    orderDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取地址失败');
  }
};

const submitOrder = async () => {
  console.log(selectedAddressId.value)
  if (!selectedAddressId.value) {
    ElMessage.error('请选择收货地址');
    return;
  }
  const orderItems = selectedRows.value.map(row => ({
    // 假设 row.product 是产品对象
    ...row.product,
    price: row.attributeProduct?.price || row.product.price,
    buyNum: row.cart.quantity
  }));
    const response = await createOrder(
      orderItems,
      selectedAddressId.value
    );
  if (response.data.state){
    ElMessage.success('订单提交成功');
    orderDialogVisible.value = false;
    console.log(response.data.data[0])
    // 查询购物车
    for (const item of selectedRows.value) {
      await deleteCartItem(item.cart.cartId);
    }
    await fetchCartItems()
    await payGO(response.data.data[0])
  }else{
    ElMessage.success('订单提交失败');
  }
};
onMounted(() => {
  fetchCartItems();
});
</script>

<style scoped lang="scss">
@import url("@/common/styles/ShowNumber.scss");
.toBold{
  margin-right: 50px;
  font-size: 20px;
}
.bottom{
  position: fixed;
  bottom: 5vh;
  width: 70%;
  height: 60px;
  line-height: 60px;
  padding-left: 20px;
  margin-left: 15%;
  border-radius: 30px;
  background: gainsboro;
  span{
    margin-left: 20px;
  }
}
.attribute-item {
  display: flex;
  align-items: center;
  gap: 10px;
  height: 60px;
  .attribute-img {
    width: 50px;
    height: 50px;
    object-fit: cover;
  }
  span{
    font-size: 16px;
    margin: 5px;
  }
}
</style>
